package com.jzo2o.orders.manager.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.jzo2o.api.trade.RefundRecordApi;
import com.jzo2o.api.trade.dto.response.ExecutionResultResDTO;
import com.jzo2o.orders.base.model.domain.OrdersRefund;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import com.jzo2o.orders.manager.service.IOrdersRefundService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class RefundOrderHandler {

    @Resource
    private IOrdersRefundService refundService;
    @Resource
    private IOrdersManagerService ordersManagerService;

    @XxlJob(value = "handleRefundOrders")
    public ReturnT handleRefundOrders() {
        log.info("执行退款定时任务");
//        查询退款的记录
        List<OrdersRefund> refundList = refundService.queryRefundOrderListByCount(10);
        if (CollectionUtil.isEmpty(refundList)){
            log.info("没有需要退款的订单，结束");
            return ReturnT.SUCCESS;
        }
//        调用支付服务的接口执行退款
        requestRefundOrder(refundList);
//        修改订单状态，删除退款记录
        return ReturnT.SUCCESS;
    }

    @Resource
    private RefundRecordApi refundRecordApi;

    private void requestRefundOrder(List<OrdersRefund> refundList) {
        for (OrdersRefund ordersRefund : refundList) {
//        远程调用支付服务接口，进行退款
            ExecutionResultResDTO resultResDTO = refundRecordApi.refundTrading(ordersRefund.getTradingOrderNo(), ordersRefund.getRealPayAmount());
//        修改订单状态，删除退款记录
            ordersManagerService.refundOrder(ordersRefund.getTradingOrderNo(),resultResDTO);
        }

    }
}
